var Emitter = require('emitter');
var ease = require('ease');

function Animation(b, c, d, type) {
  Emitter.call(this);
  this.isAnimating = false;
  this.timeout = 1000 / 60;
  this.startTime = 0;
  this.b = b;
  this.c = c;
  this.d = d || 500;
  this.type = type || 'outExpo';
  this.value = b;
  this.totalTime = d;
}

Animation.prototype = new Emitter();

Animation.prototype.animate = function() {
  if (this.isAnimating) {
    return;
  }
  this.isAnimating = true;
  this.startTime = Date.now();
};

Animation.prototype.step = function(now) {
  if (!this.isAnimating) {
    return;
  }
  var b = this.b, c = this.c, d = this.d;
  var t = (now || Date.now()) - this.startTime;
  if (b == c) {
    this.stop();
    return;
  }

  if (t >= d) {
    this.stop();
    return;
  }

  if ((c > b && this.value >= c) || (c < b && this.value <= c)) {
    this.stop();
    return;
  }

  var p = t / d;
  var val = ease[this.type](p);
  this.value = b + (c - b) * val;
  this.emit('step', this.value);
};

Animation.prototype.stop = function() {
  if (!this.isAnimating) {
    return;
  }
  this.isAnimating = false;
  this.startTime = 0;
  this.emit('end');
};

Animation.prototype.abort = function() {
  if (!this.isAnimating) {
    return;
  }

  this.isAnimating = false;
  this.startTime = 0;
}

module.exports = Animation;
